package com.ssb.admin.config.shiro;

import com.ssb.admin.common.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import java.util.concurrent.atomic.AtomicInteger;

/**
 */
@Slf4j
public class OauthHashedCredentialsMatcher extends HashedCredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {

        String loginName = (String) authcToken.getPrincipal();

        boolean matches = super.doCredentialsMatch(authcToken, info);
        if (matches) {
            // clear retry count
            ShiroUtils.clearPwdRetryCount(loginName);
        }else {
            // retry count + 1
            AtomicInteger retryCount = ShiroUtils.getPwdRetryCount(loginName);
            int nextCount = retryCount.incrementAndGet();
            log.info("###【密码错误次数】登陆名/错误次数："+loginName+"=="+nextCount);
            ShiroUtils.setPwdRetryCount(loginName, retryCount);
            if (nextCount > 5) {
                // if retry count > 5 throw
                throw new ExcessiveAttemptsException();
            }
        }
        return matches;
    }

}
